import React, { useState, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';
import { Image, List, InfiniteScroll } from 'antd-mobile';

import { addFilmList } from '../../redux/action/FilmActionCreator';

const pageSize = 10;

const useNowPlaying = (props) => {
  const { cityId, list, addFilmList } = props;
  const [hasMore, setHasMore] = useState(true);
  const pageNumRef = useRef(Math.ceil(list.length / pageSize) + 1);

  const loadMore = useCallback(
    async (isRetry) => {
      console.log('lodMore', isRetry);
      setHasMore(false);
      const res = await addFilmList(pageNumRef.current, pageSize, 1, cityId);
      const { films } = res.payload;
      setHasMore(films.length > 0);
      pageNumRef.current++;
    },
    [cityId, pageNumRef, addFilmList]
  );

  return {
    list,
    hasMore,
    loadMore,
  };
};

const NowPlaying = (props) => {
  const { list, hasMore, loadMore } = useNowPlaying(props);

  const navigate = useNavigate();
  return (
    <div>
      <List mode="card">
        {list.map((item) => (
          <List.Item
            key={item.filmId}
            prefix={
              <Image
                src={item.poster}
                fit="cover"
                width={66}
                height={92}
              />
            }
            description={
              <div>
                <div style={{ visibility: item.grade ? '' : 'hidden' }}>
                  观众评分：{item.grade}
                </div>
                <div>
                  主演：{item.actors.map((actor) => actor.name).join(' ')}
                </div>
                <div>
                  {item.nation} | {item.runtime} 分钟
                </div>
              </div>
            }
            clickable={false}
            onClick={() => navigate(`/film/detail/${item.filmId}`)}
          >
            {item.name}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll
        loadMore={loadMore}
        hasMore={hasMore}
      />
    </div>
  );
};

const MapStateToPropsParam = (state) => {
  return {
    cityId: state.CityReducer.city.id,
    list: state.FilmReducer.filmList,
  };
};

const MapDispatchToPropsParam = {
  addFilmList,
};

export default connect(
  MapStateToPropsParam,
  MapDispatchToPropsParam
)(NowPlaying);
